package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceimpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;


    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverlist=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime begintime =LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime =LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",begintime);
            map.put("end",endtime);
            map.put("status", Orders.COMPLETED);
            Double turnover =orderMapper.getsumbymap(map);
            turnover=turnover==null?0.0:turnover;
            turnoverlist.add(turnover);
        }

        String join1=StringUtil.join(",", turnoverlist);

        String join = StringUtil.join(",", dateList);
        TurnoverReportVO build = TurnoverReportVO.builder()
                .dateList(join)
                .turnoverList(join1)
                .build();


        return build;
    }

    @Override
    public UserReportVO getuserstatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
        }


        List<Integer> newuserlist=new ArrayList<>();

        List<Integer> userlist=new ArrayList<>();

        for (LocalDate localDate : dateList) {
            LocalDateTime begintime =LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime =LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("end",endtime);

            Integer countuser = userMapper.countbymap(map);
            map.put("begin",begintime);
            Integer countnewuser = userMapper.countbymap(map);
            countuser=countuser==null?0:countuser;
            countnewuser=countnewuser==null?0:countnewuser;
            newuserlist.add(countnewuser);
            userlist.add(countuser);
        }

        UserReportVO build = UserReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .newUserList(StringUtil.join(",", newuserlist))
                .totalUserList(StringUtil.join(",", userlist))
                .build();
        return build;


    }

    @Override
    public OrderReportVO getorderstatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
        }

        List<Integer> sumlist=new ArrayList<>();
        List<Integer> validlist=new ArrayList<>();


        for (LocalDate localDate : dateList) {
            LocalDateTime begintime =LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime =LocalDateTime.of(localDate, LocalTime.MAX);
            Integer sum = getordercount(begintime, endtime, null);
            Integer valid = getordercount(begintime, endtime, Orders.COMPLETED);

            sumlist.add(sum);
            validlist.add(valid);

        }

        //订单总数
        Integer sumall = sumlist.stream().reduce(Integer::sum).get();
        Integer validall = validlist.stream().reduce(Integer::sum).get();
        Double finish = 0.0;
        if (sumall!=0) {
             finish=validall.doubleValue()/sumall;
        }

        OrderReportVO build = OrderReportVO.builder()
                .dateList(StringUtil.join(",", dateList))
                .orderCountList(StringUtil.join(",", sumlist))
                .validOrderCountList(StringUtil.join(",", validlist))
                .totalOrderCount(sumall)
                .validOrderCount(validall)
                .orderCompletionRate(finish)
                .build();
        return build;

    }

    @Override
    public SalesTop10ReportVO gettop10(LocalDate begin, LocalDate end) {
        LocalDateTime begintime =LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endtime =LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.getgoodsSalesDTO(begintime, endtime);

        List<String> namelist = goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberlist = goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        SalesTop10ReportVO build = SalesTop10ReportVO.builder()
                .nameList(StringUtil.join(",", namelist))
                .numberList(StringUtil.join(",", numberlist))
                .build();
        return build;
    }

    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        LocalDate datebegin = LocalDate.now().minusDays(30);
        LocalDate dateend = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(datebegin, LocalTime.MIN), LocalDateTime.of(dateend, LocalTime.MAX));

        String filePath = "D:\\changqiongwaimai\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx";

        try {InputStream in = new FileInputStream(filePath);
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet1 = workbook.getSheet("sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间："+datebegin+"至"+dateend);
            XSSFRow row3 = sheet1.getRow(3);
            row3.getCell(2).setCellValue(businessDataVO.getTurnover());
            row3.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row3.getCell(6).setCellValue(businessDataVO.getNewUsers());
            XSSFRow row4 = sheet1.getRow(4);
            row4.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row4.getCell(4).setCellValue(businessDataVO.getUnitPrice());



            //填充订单明细
            for (int i = 0; i < 30; i++) {
                LocalDate date = datebegin.plusDays(i);
                BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));


                XSSFRow row = sheet1.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO1.getNewUsers());


            }


            //输出流下载文件
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


    private Integer getordercount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map=new HashMap<>();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);

        Integer sum=orderMapper.getcountorders(map);
        return sum==null?0:sum;
    }
}
